<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>商品详情</title>
    <!--jquery-->
    <script type="text/javascript" src="jquery/jquery-3.6.0.js"></script>
    <!--bootstrap-->
    <link rel="stylesheet" type="text/css" href="bootstrap-3.4.1/bootstrap.css">
    <script type="text/javascript" src="bootstrap-3.4.1/bootstrap.js"></script>
    <!--jquery-validator-->
    <script type="text/javascript" src="jquery-validation/jquery.validate.js"></script>
    <script type="text/javascript" src="jquery-validation/localization/messages_zh.js"></script>
    <!--jquery-json-->
    <script type="text/javascript" src="jquery/json/jquery.json.min.js"></script>
    <!--md5-->
    <script type="text/javascript" src="md5/md5.js"></script>
    <!--common-->
    <script type="text/javascript" src="js/common.js"></script>
</head>
<body>
<div class="panel panel-heading">
    <div class="panel-heading">秒杀商品详情</div>
    <div class="panel-body">
        <span id="userTip">您还没有登录，请登录后再操作</span>
        <span>没有收获地址的提示。。。</span>
    </div>


    <table class="table" id="goods">
        <tr>
            <td>商品名称</td>
            <td colspan="3" id="goodsName"></td>
        </tr>
        <tr>
            <td>商品图片</td>
            <td colspan="3"><img id="goodsImg" width="200" height="200"/></td>
        </tr>
        <tr>
            <td>秒杀开始时间</td>
            <td id="startTime"></td>
            <td>
                <!--隐藏标签，防止只有秒杀状态为0时，才会有remainSeconds-->
                <input type="hidden" id="remainSeconds">
                <!--<span th:if="${seckillStatus eq 0}">秒杀倒计时：<span id="countDown"
                                                                th:text="${remainSeconds}"></span>秒</span>
                <span th:if="${seckillStatus eq 1}">秒杀进行中</span>
                <span th:if="${seckillStatus eq 2}">秒杀已结束</span>-->
                <span id="seckillTip"></span>
            </td>
            <td>
                <!--<form id="seckillForm" method="get" action="/seckill/doSeckill">
                    <input type="hidden" name="goodsId" id="goodsId"/>
                    <button class="btn btn-primary btn-block" type="submit" id="buyButton">立即秒杀</button>
                </form>-->
                <div class="row">
                    <div class="form-inline">
                        <img id="captchaImg" width="130" height="32" onclick="refreshCaptcha()" style="display: none">
                        <input id="captcha" class="form-control" style="display: none">
                        <!--TODO 前端按钮要做防抖动处理，防止快速点击，短时间内重复提交-->
                        <button class="btn btn-primary" type="button" id="buyButton"
                                onclick="getSeckillPath()">立即秒杀
                            <input type="hidden" name="goodsId" id="goodsId"/>
                        </button>
                    </div>
                </div>

            </td>
        </tr>
        <tr>
            <td>商品原价</td>
            <td colspan="3" id="goodsPrice"></td>
        </tr>
        <tr>
            <td>秒杀价</td>
            <td colspan="3" id="seckillPrice"></td>
        </tr>
        <tr>
            <td>库存数量</td>
            <td colspan="3" id="stockCount"></td>
        </tr>
    </table>
</div>

</body>

<script>

    $(function () {
        getDetail();
    });

    function getDetail() {
        var goodsId = getQueryString("goodsId");
        $.ajax({
            url: "/goods/detail/" + goodsId,
            /*async: false,countDown()的执行方法放在了getDetail()方法的下面，要设置为同步才不会影响countDown方法的执行，这里直接放到render()方法下面不需要设置为同步了*/
            type: 'GET',
            success: function (data) {
                if (data.code == 200) {
                    render(data.obj);
                    countDown();
                } else {
                    alert("客户端请求出错");
                }
            },
            error: function () {
                alert("客户端请求出错");
            }
        });
    }

    function render(detail) {
        var user = detail.user;
        var goods = detail.goods;
        var remainSeconds = detail.remainSeconds;
        if (user) {
            $("#userTip").hide();
        }
        $("#goodsName").text(goods.goodsName);
        $("#goodsImg").attr("src", goods.goodsImg);
        $("#startTime").text(new Date(goods.startDate).format("yyyy-MM-dd HH:mm:ss"));
        $("#remainSeconds").val(remainSeconds);
        $("#goodsId").val(goods.id);
        $("#goodsPrice").text(goods.goodsPrice);
        $("#seckillPrice").text(goods.seckillPrice);
        $("#stockCount").text(goods.stockCount);

    }

    /**
     * 秒杀倒计时
     */
    function countDown() {
        var remainSeconds = $("#remainSeconds").val();
        var timeout;
        if (remainSeconds > 0) {
            // 秒杀还未开始
            $("#buyButton").attr("disabled", true);
            $("#seckillTip").html("秒杀倒计时：" + remainSeconds + "秒");
            timeout = setTimeout(function () {
                $("#remainSeconds").val(remainSeconds - 1);
                countDown();
            }, 1000);
        } else if (remainSeconds == 0) {
            // 秒杀进行中
            $("#buyButton").attr("disabled", false);
            if (timeout) {
                // 清除倒计时
                clearTimeout(timeout);
            }
            $("#seckillTip").html("秒杀进行中");
            refreshCaptcha();
            $("#captchaImg").show();
            $("#captcha").show();
        } else {
            $("#buyButton").attr("disabled", true);
            $("#seckillTip").html("秒杀已经结束");
            $("#captchaImg").hide();
            $("#captcha").hide();
        }
    }

    //获取秒杀接口的路径
    function getSeckillPath() {
        var goodsId = $("#goodsId").val();
        var captcha = $("#captcha").val();
        $.ajax({
            url: "seckill/path",
            type: "GET",
            data: {
                goodsId: goodsId,
                captcha: captcha
            },
            success: function (data) {
                if (data.code == 200) {
                    var path = data.obj;
                    doSeckill(path);
                } else {
                    alert(data.message);
                }
            },
            error: function () {
                alert("客户端请求错误");
            }
        });
    }

    function doSeckill(path) {
        $.ajax({
            url: 'seckill/' + path + '/doSeckill',
            type: 'POST',
            data: {
                goodsId: $("#goodsId").val()
            },
            success: function (data) {
                if (data.code == 200) {
                    // window.location.href = "/orderDetail.htm?orderId=" + data.obj.id;
                    getResult($("#goodsId").val());
                } else {
                    alert(data.message);
                }
            },
            error: function () {
                alert("客户端请求错误");
            }
        });
    }

    function getResult(goodsId) {
        // TODO 按钮需要显示在加载中
        $.ajax({
            url: '/seckill/getResult',
            type: 'GET',
            data: {
                goodsId: goodsId
            },
            success: function (data) {
                if (data.code == 200) {
                    var result = data.obj;
                    if (result < 0) {
                        alert("秒杀失败");
                    } else if (result == 0) {
                        // 排队中
                        setTimeout(function () {
                            getResult(goodsId);
                        }, 50);//真实场景中定时可以设置的长一点，比如说200ms，可以减轻服务器以及数据库压力，这里只是为了查看效果
                    } else {
                        var confirmResult = confirm("恭喜您，秒杀成功！查看订单？");
                        if (confirmResult == true) {
                            window.location.href = "/orderDetail.htm?orderId=" + result;
                        } else {

                        }
                    }
                } else {
                    alert("秒杀失败");
                }
            },
            error: function () {
                alert("秒杀失败");
            }
        });
    }

    function refreshCaptcha() {
        $("#captchaImg").attr("src", "/seckill/captcha?goodsId=" + $("#goodsId").val() + "&time=" + new Date());
    }
</script>
</html>